<template>
  <div class="content">
    <!-- 搜索 -->
    <div class="from-grap">
      <el-form ref="listFilterRef" :model="list.filter" inline class="list-filter">
        <el-form-item prop="channelName">
          <el-input
            v-model="list.filter.channelName"
            placeholder="渠道名称"
            clearable
          >
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </el-form-item>
        <el-form-item prop="channelType">
          <KiSelect
            v-model="list.filter.channelType"
            :options="['自有渠道', '平台渠道']"
            placeholder="渠道类型"
          />
        </el-form-item>
        <el-form-item prop="status">
          <KiSelect
            :index.sync="list.filter.status"
            :options="['停用', '启用']"
            placeholder="渠道状态"
          />
        </el-form-item>
        <el-form-item prop="authMerchant">
          <KiSelect
            v-model="list.filter.authMerchant"
            :options="['未开通', '已经开通']"
            placeholder="商户授权状态"
          />
        </el-form-item>
        <el-form-item prop="authScenic">
          <KiSelect
            v-model="list.filter.authScenic"
            :options="['未开通', '已开通']"
            placeholder="景区授权状态"
          />
        </el-form-item>
        <el-form-item prop="authHotel">
          <KiSelect
            v-model="list.filter.authHotel"
            :options="['未开通', '已开通']"
            placeholder="酒店授权状态"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total,prev, pager, next"
        :current-page="table.currentPage"
        :total="table.total"
        :page-size="table.pageSize"
        @current-change="handleSizeChange"
      ></el-pagination>
    </div>
    <!-- 表格 -->
    <el-table
      :data="table.tableData"
      border
      style="width: 100%"
      v-loading="Tloading"
    >
      <el-table-column
        v-for="item in table.tableProps"
        :key="item.id"
        :prop="item.prop"
        :align="item.align"
        :label="item.label"
        :width="item.width ? item.width : ''"
      >
        <template slot-scope="scope">
          <ex-slot
            v-if="item.render"
            :render="item.render"
            :row="scope.row"
            :index="scope.$index"
            :column="item"
          />
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开通商户授权" align="center">
        <template slot-scope="scope">
          <el-checkbox
            :disabled="!showType"
            v-model="table.tableData[scope.$index].authMerchant"
            @change="checkboxChange1(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="开通景区授权" align="center">
        <!-- 选择框 -->
        <template slot-scope="scope">
          <el-checkbox
            size="medium"
            :disabled="!showType"
            v-model="table.tableData[scope.$index].authScenic"
            @change="checkboxChange2(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column label="开通酒店授权" align="center">
        <template slot-scope="scope">
          <el-checkbox
            size="medium"
            :disabled="!showType"
            v-model="table.tableData[scope.$index].authHotel"
            @change="checkboxChange3(scope.row)"
          ></el-checkbox>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="showType" slot="footer" class="dialog-footer">
      <el-button @click="() => $emit('refresh')">取消</el-button>
      &nbsp;
      <el-button type="primary" :loading="commitLoading" @click="submit()">
        确定
      </el-button>
    </div>
  </div>
</template>
<script>
// 自定义内容的组件
var exSlot = {
  functional: true,
  props: {
    row: Object,
    render: Function,
    index: Number,
    column: {
      type: Object,
      default: null
    }
  },
  render: (h, data) => {
    const params = {
      row: data.props.row,
      index: data.props.index
    }
    if (data.props.column) params.column = data.props.column
    return data.props.render(h, params)
  }
}
// 引入方审核
import { getUserInfo } from '@/utils/auth'
export default {
  name: 'authorizer_manage',
  props: {
    showType: {
      type: Number,
      default: 0
    }
  },
  components: { exSlot },
  data () {
    return {
      companyId: null,
      Tloading: false,
      selectData: [],
      bufferData: [], //缓存原表数据，便于后期提交检测操作
      commitLoading: false,
      list: {
        filter: {
          authScenic: null,
          authMerchant: null,
          authHotel: null,
          channelName: '',
          channelType: null,
          status: null
        }
      },
      table: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
        tableData: [],
        tableProps: [
          { prop: 'channelId', label: '渠道id', align: 'center', width: 120 },
          {
            prop: 'channelName',
            label: '渠道名称',
            align: 'center',
            width: 120
          },
          {
            prop: 'channelType',
            label: '渠道类型',
            align: 'center',
            width: 120,
            render: (h, pramas) => {
              return h(
                'span',
                pramas.row.channelType == 2 ? '平台渠道' : '自有渠道'
              )
            }
          },
          {
            prop: 'status',
            label: '渠道状态',
            align: 'center',
            width: 120,
            render: (h, pramas) => {
              return h('span', pramas.row.status == 1 ? '启用' : '停用')
            }
          }
        ]
      },
      userInfo: getUserInfo()
    }
  },
  watch: {
    'list.filter': {
      handler (v) {
        this.table.currentPage = 1
        this.getTableList()
      },
      deep: true
    },
    Tloading (n) {
      // 辅助回显
      if (!n) {
        this.echo()
      }
    },
    '$route.query': {
      immediate: true,
      handler (n) {
        if (n?.companyId) {
          this.open(n)
        }
      }
    }
  },
  methods: {
    // 弹框打开时初始化
    open (data) {
      this.companyId = data.companyId
      this.selectData = []
      this.table.currentPage = 1
      this.table.total = 0
      this.commitLoading = false
      this.reset()
      this.getTableList()
    },
    // 重置
    reset () {
      this.list.filter = {
        authScenic: null,
        authMerchant: null,
        authHotel: null,
        channelName: '',
        channelType: null,
        status: null
      }
    },
    async handleSizeChange (pageIndex) {
      this.table.currentPage = pageIndex
      await this.getTableList()
    },
    submit () {
      //  this.$emit('refresh');提交后执行刷新列表操作
      this.commitLoading = true
      let data = this.selectData.map(item => {
        return {
          channelId: item.channelId,
          authScenic: item.authScenic ? 1 : 0,
          authMerchant: item.authMerchant ? 1 : 0,
          authHotel: item.authHotel ? 1 : 0
        }
      })
      this.$POST(
        '/company-channel/updateOrInsert',
        Object.assign({ companyId: this.companyId }, { list: data })
      )
        .then(res => {
          if (res.errorCode == '00000') {
            this.$swal.info('提交成功')
            this.$emit('refresh')
          } else {
            this.commitLoading = false
            this.$swal.warning('提交失败请重新提交！')
            this.$emit('refresh')
          }
        })
        .catch(err => {
          this.commitLoading = false
          this.$swal.warning('提交失败请重新提交！')
          this.$emit('refresh')
        })
    },
    // 开通商户授权authMerchant
    checkboxChange1 (row) {
      this.filterData(row)
    },
    // 开通景区授权authScenic
    checkboxChange2 (row) {
      this.filterData(row)
    },
    // 开通景区授权authHotel
    checkboxChange3 (row) {
      this.filterData(row)
    },
    filterData (row) {
      // 思路：1、如果this.selectData中没数据，就直接push当前数据，
      //2、 如果this.selectData有数据
      // 将在this.selectData数组中已经存在该channelId的对象删除掉再重新添加该条数据（新数据）
      if (this.selectData.length) {
        this.selectData = this.selectData.filter(it => {
          let bs = it.channelId != row.channelId
          return bs
        })
      }
      // 思路：如果当用户操作某一行，但是又和原来数据没区别时（还原原来数据状态时），
      // 不应将该条数据提交，所以不用提交该条数据，也就是不需要储存pd标识，如果用户还原操作数据，ps就为true
      let pd = false
      this.bufferData.forEach(i => {
        let pd1 =
          i.channelId == row.channelId &&
          i.authMerchant == row.authMerchant &&
          i.authScenic == row.authScenic &&
          i.authHotel == row.authHotel
        if (pd1) pd = true
      })
      if (!pd) this.selectData.push(row)
    },
    // 回显：监听当列表数据加载时，调用该方法（防止列表数据还没加载完成就执行了该方法）
    echo () {
      // 思路：将选择的数据存起来，当刷新当前页面时，轮巡当前列表数据，
      // 如果存在与存储数据相同的，就改变当前列表数据勾选属性
      if (this.selectData.length) {
        this.selectData.forEach(ch => {
          this.table.tableData = this.table.tableData.map(ol => {
            if (ch.channelId == ol.channelId) {
              ol.authMerchant = ch.authMerchant
              ol.authScenic = ch.authScenic
              ol.authHotel = ch.authHotel
            }
            return ol
          })
        })
      }
    },
    getTableList () {
      this.Tloading = true
      let data = Object.assign(
        {
          companyId: this.companyId,
          pageNo: this.table.currentPage,
          pageSize: this.table.pageSize
        },
        this.list.filter
      )
      data.channelType =
        this.list.filter.channelType == 1
          ? 2
          : this.list.filter.channelType == 0
          ? 1
          : ''
      if (!this.showType) data.onlyAuth = true
      this.$POST('sot-admin-api/sys/company-channel/queryForPage', data)
        .then(res => {
          let datas = res.data.records
          datas.forEach(item => {
            item.authMerchant == 1
              ? (item.authMerchant = true)
              : (item.authMerchant = false)
            item.authScenic == 1
              ? (item.authScenic = true)
              : (item.authScenic = false)
            item.authHotel == 1
              ? (item.authHotel = true)
              : (item.authHotel = false)
          })
          this.table.tableData = datas
          // this.$lo.cloneDeep深拷贝一份原始数据
          this.bufferData = this.$lo.cloneDeep(datas)
          this.table.total = res.data.total
          this.Tloading = false
        })
        .catch(err => {
          this.Tloading = false
          this.table.tableData = []
        })
    }
  }
}
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 20px 0;
}
.dialog-footer {
  margin: 40px 40px;
  text-align: right;
}
</style>
